const router = require("express")();
module.exports = router;

const db = require("../core/Data");
const User = require("../core/User");
const JSON_BODY = require('body-parser').json();

const loginStatus = ['成功登录', '验证失败', 'salt格式有误', 'salt已过期'];
router.post("/login", JSON_BODY, async (req, res) => {

    let time = Date.now();
    let data = req.body || {};
    let user = await db.getUserByName(data.username);

    if (!user) return res.json({ success: false, result: "验证失败" });

    let result = User.auth(data.password, data.salt, user.password, time);

    let success = !result;
    if (success) User.setToken(time, user, res);

    res.json({ success: success, result: loginStatus[result] });
});

router.post("/create", User.middle_checker(true), JSON_BODY,async (req, res, next) => {

    let data = req.body || {};
    let url = data.url;
    let expiresDay = Math.max(parseInt(data.expires) || 0, 0);

    try {
        new URL(url);
    } catch (err) {
        return res.json({ success: false, err: "" + err });
    }

    let shortUrl = await db.createUrl(req.user, url, expiresDay);
    if (shortUrl) return res.json({ success: true, id: shortUrl });
    else return res.json({ success: false, err: "无法生成" });

});

router.post('/login-info', (req, res) => {
    return res.json({ time: Date.now(), salt: db.statics.public_salt }).end();
});